package com.wzh.ojcodesandbox.codesandbox.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.wzh.ojcodesandbox.codesandbox.CodeSandbox;
import com.wzh.ojcodesandbox.model.ExecuteCodeRequest;
import com.wzh.ojcodesandbox.model.ExecuteCodeResponse;
import com.wzh.ojcodesandbox.model.ExecuteMessage;
import com.wzh.ojcodesandbox.model.entity.JudgeInfo;
import com.wzh.ojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author wzh
 * 通过process类以控制控制台执行对应的编译运行语句来完成代码的运行
 */
public class JavaNativeOldCodeSandbox implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    //       黑名单
    private static final List<String> blackList = Arrays.asList("File", "exec");

    private static final WordTree wordTree;

    static {
//        初始话字典数 使用字典树可以节约空间，而且在进行查询的时候也会更加的快速
        wordTree = new WordTree();
        wordTree.addWords(blackList);
    }

    /**
     * 超时限制
     */
    private static final long TIME_OUT = 500;

    public static void main(String[] args) {
        JavaNativeOldCodeSandbox javaNativeCodeSandbox = new JavaNativeOldCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String code = executeCodeRequest.getCode();
        List<String> input = executeCodeRequest.getInputList();
//        校验黑名单
        FoundWord foundWord = wordTree.matchWord(code);
        if (foundWord != null) {
            System.out.println("包含禁止词:" + foundWord.getFoundWord());
            return null;
        }
//             将用户代码另存为文件  获取用户当前的工作目录
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
//        判断全局代码目录是否存在
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
//      将用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
//        使用hutool工具包将代码写入指定路径
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
//        执行编译
        ExecuteMessage executeMessage = compileFile(userCodeFile);
        System.out.println(executeMessage);
//        运行
        List<ExecuteMessage> executeMessages = runFile(userCodeFile, input);
//        获取输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessages);
//      文件清理
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("文件删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
//            -xmx256表示jvm可以使用的最大的堆内存 jvm的堆内存限制，不等同于系统实际占用的最大资源，科能会超出
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            Process runProcess = null;
            try {
//                开启一个新的子进程
                runProcess = Runtime.getRuntime().exec(runCmd);
//                超时控制
                Process finalRunProcess = runProcess;
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了,终端");
//                        todo 此处需要判断这个runProcess是否是还在运行
                        finalRunProcess.destroy();
                    } catch (InterruptedException e) {
//                        todo此处可以返回超时信息
                        e.printStackTrace();
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                if (executeMessage.getExitValue() != 0) {
                    throw new RuntimeException("运行代码时出现异常");
                }
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return executeMessageList;
    }

    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        long maxTime = 0;
        List<String> outputList = new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessageList) {
            if (StrUtil.isNotBlank(executeMessage.getErrorMessage())) {
                executeCodeResponse.setMessage(executeMessage.getErrorMessage());
//                执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        调用第三方库来获取内存占用，非常麻烦，此处不建议实现
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }


    /**
     * 6、获取错误响应
     * 当程序抛出异常时返回错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }


}
